package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;

/**
 * 线程任务负责与指定的客户端进行HTTP交互
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);
        out.write(10);
    }

    @Override
    public void run() {
        try {
            //1.解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            //2.处理请求
            /*
             * 常用的相对路径：类加载路径
             * 定位类加载路径
             * 任何当前项目中的类的类名，通常在哪个类中需要访问类加载路径就用哪个类
             * 类名.class.getClassLoader().getResource(".")
             */
            // 类加载路径: target/classes
            File root = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            File staticDir = new File(root, "static");
//            File file = new File(staticDir, "index.html");
            String path = request.getUri();
            File file = new File(staticDir, path);
            // 发送响应状态行
            println("HTTP/1.2 200 OK");

            // 发送响应头
            println("Content-Type: text/html");
            println("Content-Length: " + file.length());

            println("");

            //3.发送响应正文
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            int len;
            byte[] buffer = new byte[1024 * 10];
            while ((len = fis.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
